package com.kehongborui.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-08-02
 */
@Controller
@RequestMapping("/file")
public class UploadController {
    /**
     * 上传文件方法
     * @param uploadFile
     * @param request
     * @param map
     */
    @RequestMapping("/upload")
    public String upload(MultipartFile uploadFile, HttpServletRequest request, ModelMap map) throws IOException {
        // 获取原始文件名称
        String fileName = uploadFile.getOriginalFilename();
        // 获取文件保存的位置(路径)
        String realPath = request.getServletContext().getRealPath("/");

        File file = new File(realPath + "/" + fileName);

        // 将上传的文件流写入到新建的file文件中
        uploadFile.transferTo(file);

        // 设置图片回显路径
        map.addAttribute("fileUrl", "/" + fileName);
        return "result";
    }
}
